package kite.sso.service.comp;

import kite.sso.message.UserEntity;
import kite.sso.model.KiteUser;
import kite.sso.service.KiteSysService;
import kite.sso.service.KiteUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述: <br>
 * 所属包名: kite.sso.service.custom<br>
 * 创建人　: 白剑<br>
 * 创建时间: 2018/06/04 23:19:28<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Component
public class KiteUserDetailsService implements UserDetailsService {

    private static Logger logger = LoggerFactory.getLogger(KiteUserDetailsService.class);

    @Autowired
    private KiteUserService kiteUserService;

    @Autowired
    private KiteSysService kiteSysService;

    public KiteUserDetailsService() {
        super();
    }

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {

        KiteUser kiteUser = kiteUserService.getUserById(userId);
        if (null == kiteUser) {
            logger.info("未查找到用户：{}", userId);
            return null;
        }

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(kiteUser, userEntity);
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ADMIN")); // 暂时还没有用，各个子系统自己控制角色
        authorities.add(new SimpleGrantedAuthority("USER"));
        userEntity.setAuthorities(authorities);
        userEntity.setUserAccessSys(kiteSysService.getUserAccessSys(userId));
        logger.info("查询到用户：{}，其权限为：{}", userEntity, authorities);

        return userEntity;
    }
}
